//1.导入 express
const express = require("express")

//2.创建 express 服务
const app = express();

//4.导入 cors 跨域中间件
const cors = require("cors");
//4.1注册 cors() 中间件
app.use(cors());
const path = require("path")
//导入express-jwt
const {expressjwt: jwt} = require("express-jwt")
//导入密钥解密
const {jwtSecretKey} = require("./config");

//导入multer 中间件
const multer = require("multer")

//导入Joi模块 表单验证
const Joi = require("joi");

//5.导入express内置的表单解析中间件 urlencoded  x-www-form-urlencoded
app.use(express.urlencoded({extended: false}));

//8.在路由之前注册 封装一个res.cc()函数 处理信息提示
app.use(function (req, res, next) {
    //定义cc() 函数
    //参数err :错误信息，可能是对象、可能是字符串
    //状态：1:表示错误 默认 0:表示成功
    res.cc = function (err, status = 1) {
        res.send({
            status,
            message: err instanceof Error ? err.message : err,
        })
    }
    next();
})

//9.在路由之前注册token解析校验, 正则处理/api/路径的接口不做token校验
app.use(jwt({secret: jwtSecretKey, algorithms: ['HS256']}).unless({path: [/^\/(api|uploads)/]}))


//6、导入登录、注册路由模块并注册
const userRouter = require("./router/user")
app.use('/api', userRouter)

//导入个人信息路由模块并注册
const userInfoRouter = require("./router/userinfo")
app.use("/my", userInfoRouter)


//导入文章类别管理路由模块并注册
const articleCateRouter = require("./router/artcate")
app.use("/article/cate", articleCateRouter)

//导入文章管理路由模块并注册
const articleRouter = require("./router/article")
app.use("/article", articleRouter)

//导入文件上传、预览路由模块并注册
const fileRouter = require("./router/fileUpload")
app.use(fileRouter)

/*//7、导入mysql
const db = require("./db/mysql");
db.connect();//连接数据库
//检测数据库 是否连接成功
db.query("SELECT  1", function (error, results) {
    if (error) throw error;
    console.log('The solution is: ', results); //The solution is:  [ RowDataPacket { '1': 1 } ]
})*/


//定义应用级别的错误中间件
app.use((err, req, res, next) => {
    //判断表单校验错误 ValidationError
    if (err instanceof Joi.ValidationError) {
        return res.cc(err)
    }
    //判断token身份验证
    if (err.name === 'UnauthorizedError') {
        return res.cc("身份验证失败")
    }
    //文件上传
    if (err instanceof multer.MulterError) {
        return res.cc("文件上传失败")
    }

    //其他错误
    res.cc(err)
})


//3.启动服务
app.listen(3006, () => {
    console.log("server running at http://127.0.0.1:3006")
})

